import React, { ReactNode } from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router-dom';
import { connect } from 'dva';
import { Modal, Form, Table, Button, Input, Upload, Icon, message } from 'antd';
import Cookies from 'js-cookie';
import _ from 'lodash';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';

import { getRepairSysColumns, getRepairMerColumns } from '../utils';
import { checkShowOpt } from '../../utils';
import { UPLOAD_PIC, CACHE_TOKEN, CACHE_UID, SUCCESS_CODE } from '../../data';
import styles from '../style.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Dragger } = Upload;

interface StateType {
  [propName: string]: any;
}

interface PropType {
  [propName: string]: any;
}

class RepairDetailDialog extends React.PureComponent<PropType, StateType> {
  public state = {
    systemSendData: {
      dateType: -1,
      userType: -1,
      limitType: -1,
      paymentId: -3,
      searchType: 1,
      keywords: '',
      page: 1,
      size: 20,
    },
    saveData: {
      orderId: '',
      amount: 0,
    },
    systemTableData: [],
    merchantTableData: [{ status: undefined }],
    isClick: false,
    fileList: [],
    fileListLength: 0,
    uploadCount: 0,
    uploadApi: `${UPLOAD_PIC}?token=${Cookies.get(CACHE_TOKEN)}&uid=${Cookies.get(CACHE_UID)}`,
    previewVisible: false,
    previewImage: '',
    isUpload: false,
    payeeName: '',
    payeeBankId: '',
    files: '',
  };

  public systemColumns = getRepairSysColumns(this);

  public merchantColumns = getRepairMerColumns(this);

  componentDidMount() {
    const { data } = this.props;
    this.handleCheck(data);
    const dataLength = Object.keys(data).length;
    if (dataLength > 0) {
      this.hanleTableData(data);
    }
  }

  // 处理表格数据
  private hanleTableData = (data: any) => {
    const { orderId, amount } = data;
    const systemTableData = [{ ...data }];
    const saveData = { orderId, amount };
    const obj = { ...this.state, systemTableData, saveData };
    this.setState({ ...obj });
  };

  // 补单确定
  private bindEffects = (values: object) => {
    this.props.dispatch({
      type: 'recharge/repairConfirmEffect',
      payload: {
        ...values,
        ...this.state.saveData,
      },
      callback: () => {
        this.props.form.resetFields();
        this.props.confirm();
      },
    });
  };

  // 补单拒绝
  private refuseEffect = (values: any) => {
    const { orderId } = this.state.saveData;
    values.remark = values.sucReqRemark;
    delete values.sucReqRemark;
    this.props.dispatch({
      type: 'recharge/repairRefuseEffect',
      payload: {
        ...values,
        orderId,
      },
      callback: () => {
        this.props.form.resetFields();
        this.props.confirm();
      },
    });
  };

  // 补单保存
  private handleSubmit = () => {
    const { isUpload, payeeBankId, payeeName, files } = this.state;
    if (isUpload) {
      // 图片正在上传中，请稍后再试
      message.error(formatMessage({ id: 'recharge-repair.img-uploading-warning' }));
      return;
    }
    if (!files) {
      // 请先上传转账凭证！
      message.error(formatMessage({ id: 'recharge-repair-detail-dialog.certificate-warning' }));
      return;
    }
    this.props.form.validateFields((err: any, values: any) => {
      if (!err) {
        // const attachments = _.map(this.state.fileList, (item: any) => item.url).join(',');
        this.bindEffects({ ...values, attachments: files, payeeBankId, payeeName });
      }
    });
  };

  // 补单拒绝
  private handleRefuse = () => {
    this.props.form.validateFields((err: any, values: any) => {
      if (!err) {
        this.refuseEffect(values);
      }
    });
  };

  private handleCheck = (record: any) => {
    this.props.dispatch({
      type: 'recharge/checkMerchantStatusEffect',
      payload: { orderId: record.orderId },
      callback: (response: any) => {
        const { code, data } = response;
        let merchantTableData = [];
        let state = {};
        if (code === SUCCESS_CODE) {
          if (data) {
            merchantTableData = [data];
          }
          state = { ...this.state, merchantTableData, isClick: true };
        } else {
          state = { ...this.state, isClick: true };
        }
        this.setState({
          ...state,
        });
      },
    });
  };

  private handleDialogClose = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  private handleImg = (index: number) => {
    const { files } = this.state;
    const list = files.split(',');
    this.setState({
      previewImage: list[index],
      previewVisible: true,
    });
  };

  private imgDelete = (index: number) => {
    const { files } = this.state;
    const list = files.split(',');
    list.splice(index, 1);
    this.setState({
      files: list.join(','),
    });
  };

  // 渲染按钮
  private optButtonGroup = () => {
    const { showOpt } = this.props;
    const { isClick, files } = this.state;
    const fileList = files.split(',').filter((item: string) => !!item);
    const sucReqRemark = this.props.form.getFieldValue('sucReqRemark');
    const refuseAvailable = isClick && sucReqRemark;
    const confirmAvailable = isClick && fileList.length && sucReqRemark;

    const optArr = [
      // 取消
      <Button key="back" onClick={this.handleDialogClose}>
        {formatMessage({ id: 'recharge-repair.cancel-btn' })}
      </Button>,
      // 确定拒绝
      <Button key="refuse" type="primary" onClick={this.handleRefuse} disabled={!refuseAvailable}>
        {formatMessage({ id: 'recharge-repair.refuse-btn' })}
      </Button>,
      // 确定
      <Button key="submit" type="primary" onClick={this.handleSubmit} disabled={!confirmAvailable}>
        {formatMessage({ id: 'recharge-repair.confirm-btn' })}
      </Button>,
    ];
    const noOptArr = [
      // 确定
      <Button key="back" onClick={this.handleDialogClose}>
        {formatMessage({ id: 'recharge-repair.confirm-btn' })}
      </Button>,
    ];

    return showOpt ? optArr : noOptArr;
  };

  // 渲染截图
  private renderImgList = (): ReactNode => {
    const { files } = this.state;
    const fileList = files.split(',');

    return fileList.length ? (
      <ul className={styles.imgViewContianer}>
        {fileList.map((item: any, index: number) => {
          const ele = item ? (
            <li key={item}>
              <Icon
                type="close"
                className={styles.closeIcon}
                onClick={() => {
                  this.imgDelete(index);
                }}
              />
              <img
                src={item}
                alt=""
                style={{ width: '100%', height: '100%' }}
                onClick={() => {
                  this.handleImg(index);
                }}
              />
            </li>
          ) : null;
          return ele;
        })}
      </ul>
    ) : null;
  };

  render(): ReactNode {
    const self = this;
    const { getFieldDecorator } = this.props.form;
    const {
      systemTableData,
      merchantTableData,
      uploadApi,
      isUpload,
      files,
      fileListLength,
      previewVisible,
      previewImage,
    } = this.state;
    const { visible, data } = this.props;
    const imgList = files.split(',').filter((item: string) => !!item);

    const props = {
      name: 'file',
      multiple: true,
      action: uploadApi,
      accept: 'image/*',
      showUploadList: false,
      onSuccess(info: any) {
        const { code, data: infoData, message: msg } = info;
        const { uploadCount, files: infoFiles } = self.state;
        if (code === SUCCESS_CODE) {
          const list = infoFiles ? infoFiles.split(',') : [];
          if (list.length >= 3) return;

          const arr = list.length ? [...list, infoData] : [infoData];
          const str = arr.join(',');

          if (arr.length >= 3 || uploadCount === fileListLength - 1) {
            self.setState({
              isUpload: false,
              files: str,
              uploadCount: 0,
              fileListLength: 0,
            });
            return;
          }
          self.setState({
            uploadCount: uploadCount + 1,
            files: str,
          });
        } else {
          message.error(msg);
        }
      },
      beforeUpload(file: any, fileList: any) {
        const { length } = fileList;
        self.setState({
          isUpload: true,
          fileListLength: length,
        });
        return true;
      },
    };

    return (
      <Modal
        visible={visible}
        width={1100}
        title={formatMessage({ id: 'recharge-repair-detail-dialog.modal-title' })}
        onCancel={this.handleDialogClose}
        footer={this.optButtonGroup()}
      >
        {/* 系统订单详情 */}
        <h3>{formatMessage({ id: 'recharge-repair-detail-dialog.system-order-detail-title' })}</h3>
        <Table
          className={styles.tableContainer}
          size="small"
          bordered
          pagination={false}
          rowKey={(record: any, index: number) => record.orderId || index}
          columns={getRepairSysColumns(this)}
          dataSource={systemTableData}
        />
        <br />
        {/* 第三方订单详情 */}
        <h3>{formatMessage({ id: 'recharge-repair-detail-dialog.third-order-detail-title' })}</h3>
        <Table
          className={styles.tableContainer}
          size="small"
          bordered
          pagination={false}
          rowKey={(record: any, index: number) => record.orderId || index}
          columns={getRepairMerColumns(this)}
          dataSource={merchantTableData}
        />
        <Form style={{ marginTop: '10px' }}>
          {/* 备注 */}
          <FormItem label={<FormattedMessage id="recharge-repair-detail-dialog.form-remark" />}>
            {getFieldDecorator('sucReqRemark', {
              initialValue: checkShowOpt(data) ? '' : data.sucReqRemark,
              rules: [
                {
                  required: true,
                  message: formatMessage({
                    id: 'recharge-repair-detail-dialog.form-remark-required',
                  }),
                },
              ],
            })(<TextArea rows={4} disabled={!checkShowOpt(data)} />)}
          </FormItem>
        </Form>

        {checkShowOpt(data) ? (
          <div>
            {imgList.length !== 3 ? (
              <Dragger {...props}>
                <p className="ant-upload-drag-icon">
                  <Icon type="inbox" />
                </p>
                <p className="ant-upload-text">拖拽图片、或点击图片上传</p>
              </Dragger>
            ) : null}
            {this.renderImgList()}
            {isUpload ? (
              <p>{formatMessage({ id: 'recharge-repair-detail-dialog.img-upload-status' })}...</p>
            ) : null}
            <Modal
              width={1200}
              visible={previewVisible}
              footer={null}
              onCancel={() => {
                this.setState({ previewVisible: false });
              }}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </div>
        ) : null}
      </Modal>
    );
  }
}

const RepairDetailDialogContainer = Form.create({ name: 'ReviewDialog' })(RepairDetailDialog);

export default withRouter(
  connect(({ recharge }: { recharge: any }) => ({
    recharge,
  }))(RepairDetailDialogContainer),
);
